package com.example.Servlet;

import com.google.gson.Gson;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@MultipartConfig
@WebServlet(name = "FileUploadServlet", value = "/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {

    public void init() {
        // 初始化代码
    }

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // GET 请求处理
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Part part = req.getPart("newsImg");
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<>();

        if (part == null) {
            map.put("code", 400);
            map.put("msg", "未找到上传的文件");
            resp.getWriter().append(gson.toJson(map));
            return;
        }

        // 获取原始文件名
        String originalName = part.getSubmittedFileName();

        String uploadDir = req.getServletContext().getRealPath("static/upload");
        File path = new File(uploadDir);
        if (!path.exists()) {
            path.mkdirs();
        }

        // 保存文件，不重新命名
        File uploadFile = new File(path, originalName);
        if (uploadFile.exists()) {
            map.put("code", 400);
            map.put("msg", "文件已存在，请重命名后上传");
            resp.getWriter().append(gson.toJson(map));
            return;
        }

        part.write(uploadFile.getAbsolutePath());

        String contextPath = req.getContextPath();
        String fileUrl = contextPath + "/static/upload/" + originalName;

        map.put("code", 200);
        map.put("msg", "上传成功");
        map.put("filename", originalName);
        map.put("fileUrl", fileUrl); // 完整的访问 URL
        map.put("relativePath", "static/upload/" + originalName); // 相对路径

        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().append(gson.toJson(map));
    }
}